﻿using Meow.Core.Render;
using Silk.NET.Input;
using Silk.NET.Maths;
using Silk.NET.OpenGL;
using Silk.NET.Windowing;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Meow.Core
{
    public class AppWindow
    {
        IWindow _window;
        WindowOptions options;

        public Renderer renderer;
        public int fps = 30;
        public double lastTime = 0;

        public AppWindow(string title, int width, int height, int fps) 
        {
            WindowOptions options = WindowOptions.Default with
            {
                Size = new Vector2D<int>(width, height),
                Title = title,
            };

            _window = Window.Create(options);

            _window.Load += OnLoad;
            _window.Update += OnUpdate;
            _window.Render += OnRender;

            this.fps = fps;
        }

        protected virtual void Run()
        {
            _window.Run();
        }


        protected virtual unsafe void OnLoad()
        {
            IInputContext input = _window.CreateInput();
            for (int i = 0; i < input.Keyboards.Count; i++)
                input.Keyboards[i].KeyDown += KeyDown;

            renderer = new Renderer(_window.CreateOpenGL(), Color.Coral);
        }

        // These two methods are unused for this tutorial, aside from the logging we added earlier.
        protected virtual void OnUpdate(double deltaTime)
        {
        }


        protected virtual unsafe void OnRender(double deltaTime)
        {
            lastTime += deltaTime;
            if (lastTime < 1.0d / fps)
            {
                return;
            }

            lastTime -= 1.0d / fps;

            renderer.OnRender(fps);

        }

        protected virtual void KeyDown(IKeyboard keyboard, Key key, int keyCode)
        {
            if (key == Key.Escape)
                _window.Close();
        }
    }
}
